package com.um2.mauction.java;

import java.io.IOException;
import java.util.Set;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;


import com.um2.mauction.entity.Enchere;
import com.um2.mauction.entity.Produit;
import com.um2.mauction.entity.Vente;
import com.um2.mauction.session.impl.VenteManagerBean;
import com.um2.mauction.session.remote.VenteManagerRemote;

public class FicheVenteInitAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		ActionForward resultat = mapping.findForward("succes");
		ActionErrors errors = new ActionErrors();

		VenteManagerRemote vmanager = null;

		String idVente = request.getParameter("sale_id");
		
		if(idVente==null || Integer.parseInt(idVente)==0)
		{	
		errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("ajoutprod.statefulBean.notBound"));
		resultat = new ActionForward(mapping.getInput());
		}
		try {
			InitialContext ic = new InitialContext();

			// Liste des ventes
			vmanager = (VenteManagerRemote) ic
					.lookup(VenteManagerBean.RemoteJNDIName);

			Vente v = vmanager.getVente(Integer.parseInt(idVente));
			Produit prod = v.getItem();
			Set<Enchere> encheres = v.getBids();
			Enchere e = vmanager.getLastEnchereOfVente(Integer.parseInt(idVente));
			
			request.setAttribute("vente",v);
			request.setAttribute("produit",prod);					
			request.setAttribute("encheresVente",encheres);
			
			float lastbid=0;
			
			if (e != null)
				lastbid = e.getAmount();
			else
				lastbid = v.getMontantInitial();
			
			request.setAttribute("lbid",String.valueOf(lastbid));
			
			
		} catch (NamingException ex) {
			System.out.println("ERREUR!!" + ex.getMessage());
		}
		if (!errors.isEmpty())
			saveErrors(request, errors);
		
		return resultat;
	}
}
